<?php

/**
 * This is the model class for table "{{flats}}".
 *
 * The followings are the available columns in table '{{flats}}':
 * @property integer $id
 * @property integer $user_id
 * @property integer $type_id
 * @property integer $city_id
 * @property integer $region_id
 * @property integer $country_id
 * @property string  $street
 * @property integer $home
 * @property integer $korp
 * @property integer $lat
 * @property integer $lng
 * @property integer $guests
 * @property string  $sleeper
 * @property integer $room
 * @property integer $price
 * @property string $description
 * @property string $infrastructure
 * @property string $furniture
 * @property integer $count_show
 * @property integer $count_order
 * @property string img0
 * @property string img1
 * @property string img2
 * @property string img3
 * @property string img4
 * @property string img5
 * @property string img6
 * @property string img7
 * @property integer $is_active
 */
class Flat extends CActiveRecord {
    
    public $comfort;
    public $pubSocialNetworks;
    
    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Flat the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{flats}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('user_id, type_id, repair_id, city_id, street, home, guests, sleeper, price, description, is_active', 'required'),
            array('user_id, type_id, repair_id, city_id, region_id, country_id, guests, price, count_show, count_order, is_active', 'numerical', 'integerOnly' => true),
            array('street, lat, lng, sleeper, home, korp, infrastructure, furniture,', 'length', 'max' => 254),
            array('img0', 'file', 'types' => 'jpg, jpeg, gif, png, JPG, JPEG, GIF, PNG', 'allowEmpty' => false, 'wrongType' => 'Недопустимый формат картинки', 'on' => 'create'),
            array('img1, img2, img3, img4, img5, img6, img7', 'file', 'types' => 'jpg, jpeg, gif, png, JPG, JPEG, GIF, PNG', 'allowEmpty' => true, 'wrongType' => 'Недопустимый формат картинки', 'on' => 'create'),
            array('img0, img1, img2, img3, img4, img5, img6, img7', 'file', 'types' => 'jpg, jpeg, gif, png, JPG, JPEG, GIF, PNG', 'allowEmpty' => true, 'wrongType' => 'Недопустимый формат картинки', 'on' => 'update'),
            // Please remove those attributes that should not be searched.
            array('id, user_id, type_id, repair_id, city_id, region_id, country_id, guests, street, home, korp, lat, lng, sleeper, price, description, infrastructure, furniture, count_show, count_order, is_active', 'safe', 'on' => 'search'),
        );
    }

    protected function beforeSave() {
        if (parent::beforeSave()) {
            
            // получаю актуальные координаты
            $xml = simplexml_load_file('http://maps.google.com/maps/api/geocode/xml?address=' . $this->getAddress() . '&sensor=false');
            $this->lat = $xml->result->geometry->location->lat;
            $this->lng = $xml->result->geometry->location->lng;
            
            return true;
        }
        else
            return false;
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'user' => array(self::BELONGS_TO, 'User', 'user_id'),
            'сountry' => array(self::BELONGS_TO, 'Country', 'country_id'),
            'region' => array(self::BELONGS_TO, 'Region', 'region_id'),
            'сity' => array(self::BELONGS_TO, 'City', 'city_id'),
            'comforts' => array(self::MANY_MANY, 'Comfort', 'fl_flats_vs_comfort(flats_id, comfort_id)'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'user_id' => 'User',
            'type_id' => 'Тип недвижимости',
            'repair_id' => 'Уровень ремонта',
            'city_id' => 'Город',
            'region_id' => 'Регион',
            'country_id' => 'Страна',
            'street' => 'Улица',
            'home' => 'Дом',
            'korp' => 'Корпус',
            'lat' => 'Lat',
            'lng' => 'Lng',
            'guests' => 'Количество гостей',
            'sleeper' => 'Размещение',
            'price' => 'Стоимость за сутки',
            'description' => 'Описание',
            'infrastructure' => 'Инфраструктура',
            'furniture' => 'Мебель',
            'count_show' => 'Количество показов',
            'count_order' => 'Количество заказов',
            'img0' => 'Фото №1',
            'img1' => 'Фото №2',
            'img2' => 'Фото №3',
            'img3' => 'Фото №4',
            'img4' => 'Фото №5',
            'img5' => 'Фото №6',
            'img6' => 'Фото №7',
            'img7' => 'Фото №8',
            'is_active' => 'Is Active',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('user_id', $this->user_id);
        $criteria->compare('type_id', $this->type_id);
        $criteria->compare('repair_id', $this->repair_id);
        $criteria->compare('city_id', $this->city_id);
        $criteria->compare('region_id', $this->region_id);
        $criteria->compare('country_id', $this->country_id);
        $criteria->compare('street', $this->street, true);
        $criteria->compare('home', $this->home);
        $criteria->compare('lat', $this->lat);
        $criteria->compare('lng', $this->lng);
        $criteria->compare('sleeper', $this->sleeper);
        $criteria->compare('price', $this->price);
        $criteria->compare('description', $this->description, true);
        $criteria->compare('count_show', $this->count_show);
        $criteria->compare('count_order', $this->count_order);
        $criteria->compare('is_active', $this->is_active);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    public static function getTypeFlat() {
        return array(
            '1' => '1 комната',
            '2' => '2 комнаты',
            '3' => '3 комнаты',
            '4' => '4 комнаты',
            '5' => 'Дом',
            '6' => 'Мини-отель',
        );
    }

    public function getTypeFlatText() {
        $typeFlat = self::getTypeFlat();

        return $typeFlat[$this->type_id];
    }

    public static function getSleeper() {
        return array(
            '1' => '1',
            '2' => '2',
            '3' => '3',
            '4' => '4',
            '5' => '5',
            '6' => '5+',
        );
    }

    public static function getRepair() {
        return array(
            '1' => 'Без ремонта',
            '2' => 'Косметический ремонт',
            '3' => 'Капитальный ремонт "под евро"',
            '4' => 'Дизайнерский евроремонт',
        );
    }

    public function getRepairText() {
        $repairs = self::getRepair();

        return $repairs[$this->repair_id];
    }
    
    public function getSleeperText() {
        $repairs = self::getSleeper();

        return $repairs[$this->repair_id];
    }
    
    public function getCountryName() {
        return $this->сountry->name;
    }
    
    public function getRegionName() {
        return $this->region->name;
    }
    
    public function getCityName() {
        return $this->сity->name;
    }

    public function getAddress() {
        $city = City::model()->findByPk($this->city_id);
        $country = Country::model()->findByPk($city->country_id);
        $region = Region::model()->findByPk($city->region_id);

        $this->region_id = $city->region_id;
        $this->country_id = $city->country_id;

        $region->name =  ($region->name != 'АРК' ? $region->name . ", " : '') ;
        
        return $country->name . ", " . $region->name . $city->name . ", " . $this->street . " " . $this->home;
    }
    
    public function getPrice() {
        return $this->price. " грн./сутки";
    }
    
    public static function getPriceFromCity($cityId = false, $type = 'max') {

        $criteria = new CDbCriteria;
        $criteria->select = $type.'(price) AS price';
        $criteria->condition = 'is_active = 1';
        
        if($cityId){
            $criteria->addCondition("city_id = ".$cityId."");
        }
        
        $rez = Flat::model()->find($criteria);
        
        return $rez['price'];
    }
    
    public static function getTextStatus(){
        return array(
            0 => "Отклонено",
            1 => "Активно",
            2 => "Ожидает модерацию",
        );
    }
    
    
    public function getStatus(){
        $text = Flat::getTextStatus();
        return $text[$this->is_active];
    }
    
    public function getUserInfo(){
        return $this->user->profile->lastname . " " .  $this->user->profile->firstname . "<br />" .  $this->user->email;
    }

}